const { defineConfig } = require('@vue/cli-service');
const Components = require('unplugin-vue-components/webpack');
const { ArcoResolver } = require('unplugin-vue-components/resolvers');
const path = require('path');

module.exports = defineConfig({
  publicPath: './',
  transpileDependencies: true,
  runtimeCompiler: true,
  lintOnSave: false, // 关闭保存时 lint 检查，提升开发效率
  
  // 开发服务器配置
  devServer: {
    port: 8085,
    open: true,
    hot: true,
    compress: true,
    historyApiFallback: {
      index: '/index.html'
    },
  },

  // 路径别名和性能优化配置
  configureWebpack: config => {
    // 根据环境配置 source map
    config.devtool = process.env.NODE_ENV === 'development' ? 'eval-cheap-module-source-map' : false;
    
    // 优化模块解析
    config.resolve = {
      ...config.resolve,
      symlinks: false, // 禁用符号链接解析，提升性能
      alias: {
        '@': path.resolve(__dirname, 'src'),
        'assets': path.resolve(__dirname, 'src/assets'),
        'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js',
      },
      // 添加常用文件扩展名，提高解析速度
      extensions: ['.js', '.vue', '.json', '.ts', '.tsx'],
    };

    // 优化缓存配置
    config.cache = {
      type: 'filesystem',
      buildDependencies: {
        config: [__filename],
      },
      cacheDirectory: path.resolve(__dirname, 'node_modules/.cache/webpack'),
      maxAge: 5184000000, // 60 天缓存
    };

    // 优化性能配置
    config.optimization = {
      ...config.optimization,
      moduleIds: 'deterministic', // 使用确定性的模块 ID
      splitChunks: {
        chunks: 'all',
        cacheGroups: {
          vendors: {
            name: 'chunk-vendors',
            test: /[\\/]node_modules[\\/]/,
            priority: -10,
            chunks: 'initial',
          },
          common: {
            name: 'chunk-common',
            minChunks: 2,
            priority: -20,
            chunks: 'initial',
            reuseExistingChunk: true,
          },
        },
      },
    };

    // 添加 Arco Design 自动导入插件
    config.plugins.push(
      Components({
        resolvers: [
          ArcoResolver({
            sideEffect: true,
            importStyle: true
          })
        ],
        dts: true,
        // 排除可能与Arco Design组件冲突的自定义组件
        exclude: [/src\/components\/menu\/index\.vue$/]
      })
    );
  },

  // Webpack 链式配置
  chainWebpack: (config) => {
    // 添加 Vue 3 特性标志
    config.plugin('define').tap((definitions) => {
      Object.assign(definitions[0], {
        __VUE_OPTIONS_API__: 'true',
        __VUE_PROD_DEVTOOLS__: 'false',
        __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: 'false'
      });
      return definitions;
    });

    
    // SVG 处理
    const svgRule = config.module.rule('svg');
    svgRule.uses.clear();
    svgRule
      .test(/\.svg$/)
      .use('vue-loader')
      .loader('vue-loader')
      .end()
      .use('vue-svg-loader')
      .loader('vue-svg-loader')
      .options({
        svgo: {
          plugins: [
            { name: 'removeDoctype', active: true },
            { name: 'removeComments', active: true },
          ],
        },
      });

    // 生产环境优化
    if (process.env.NODE_ENV === 'production') {
      // 移除 console（代码分割已在 configureWebpack 中配置）
      config.optimization.minimizer('terser').tap((args) => {
        args[0].terserOptions.compress.drop_console = true;
        args[0].terserOptions.compress.drop_debugger = true;
        return args;
      });
    }

    // Bundle Analyzer
    if (process.env.ANALYZE) {
      const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
      config.plugin('bundle-analyzer').use(BundleAnalyzerPlugin);
    }
  },

  // CSS 相关配置
  css: {
    loaderOptions: {
      less: {
        lessOptions: {
          modifyVars: {
            hack: `true; @import (reference) "${path.resolve('src/assets/style/breakpoint.less')}";`,
          },
          javascriptEnabled: true,
        },
      },
    },
  },

  // 只保留需要修改的配置，其他使用默认值
  assetsDir: 'static',
  productionSourceMap: false,
  parallel: require('os').cpus().length > 1,
});